package com.leyou.user.interceptors;

import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.user.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 校验请求头中的token
 */
@Slf4j
public class PrivilegeInterceptor implements HandlerInterceptor {


    private JwtProperties jwtProp;

    public PrivilegeInterceptor(JwtProperties jwtProp){
        this.jwtProp = jwtProp;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler){

        try {
            //获取请求头
            String token = request.getHeader(jwtProp.getApp().getHeaderName());

            //解析token
            Payload<AppInfo> payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), AppInfo.class);

            AppInfo appInfo = payload.getInfo();

            List<Long> targetList = appInfo.getTargetList();  //服务调用者可访问的服务id的集合

            Long currentServiceId = jwtProp.getApp().getId();  //获取当前服务id

            //如果服务调用者可调用的服务id集合为null,或服务调用者可调用的服务不包含当前服务
            if (targetList == null || !targetList.contains(currentServiceId)){
                log.info("请求者没有访问本服务的权限！");
                return false;
            }

            log.info("服务{}正在请求资源:{}", appInfo.getServiceName(), request.getRequestURI());
            return true;
        } catch (Exception e) {
            log.error("服务访问被拒绝,token认证失败!", e);
            return false;
        }


    }
}